package com.javaweb.aop;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/16 15:07
 */

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面： 包括
 *     pointCut 切点表达式
 *    advice   增强
 *
 */
@Aspect
@Component
@Slf4j
public class DaoAspect {
    /**
     *  pointCut:
     *   - within: 针对范围    within(com.javaweb.dao..*)
     *   - execution: 针对执行点（join point）   execution(insert*(String))
     *   - args,
     *   - @within
     *   - @target
     *   - @annotation
     *
     *    Best Practice 最佳实践
     *    范围  &&  执行点
     *
     */
    @Pointcut("within(com.javaweb.dao..*)")
    public void daoLayer() {}
    @Pointcut("daoLayer() && execution(public * insert*(..))")
    public void allDaoInsert() {}

    @Pointcut("daoLayer() && execution(* select*(..))")
    public void allDaoSelect() {}




    /**
     * 增强的逻辑 advice:
     *   - before advice
     *   -  after advice (finally)
     *   - around advice
     *   - after throwing
     *   - after returning
     */

//    @Before("allDaoInsert()")
    public void logBeforeMethod(JoinPoint jp) {
        log.info("Info from logBeforeMethod before method {} invoke.",
                jp.getSignature().getName()) ;
    }


//    @After("allDaoSelect()")
    public void logAfterMethod(JoinPoint jp) {
        log.info("Info from logAfterMethod after method {} invoke.",
                jp.getSignature().getName()) ;
    }


//    @Around("allDaoSelect()")
    public Object tryCatchException(ProceedingJoinPoint pjp) {

        log.info("INFO from tryCatchExeption-Aspect for method {}",
                 pjp.getSignature().getName()) ;

        Object ret = null ;
        try {
            // BEFORE join-point
            // EXACTLY that join point:  userDao.selectOne()
            ret = pjp.proceed();
            // AFTER join-point
            log.info("INFO from tryCatchExeption-Aspect for method {}: with return {}",
                    pjp.getSignature().getName(), ret) ;
            return ret ;
        } catch (Throwable e) {
            log.error("INFO from tryCatchExeption-Aspect for method {}: {}",
                    pjp.getSignature().getName(), e.getMessage()) ;
        }
        return null ;


    }











}
